﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using XNADota.Terrain;
using System.Diagnostics;
using System.IO;
using Microsoft.Xna.Framework.Graphics;
using XNADota.GamePlay;

namespace XNADota.Graphics
{
    public class DoodadPaletteRendererContainer : PaletteRendererContainer
    {
        private static Game _Game;

        private static List<string> _DebugRecords;

        private static Dictionary<string, string> _FileNames;
        private static Dictionary<string, string> _TextureNames;
        private static Dictionary<string, Texture2D> _Textures;

        private static Dictionary<string, DoodadRenderer> _DoodadRenderer;

        public DoodadPaletteRendererContainer(Game game)
        {
            _Game = game;

            //"Data\\DestructableData.txt"
            //"Data\\Doodads.txt"

            // Create File Names
            string ConfigFileName = "Data\\DestructableData.txt";
            _FileNames = new Dictionary<string, string>();
            _TextureNames = new Dictionary<string, string>();
            _Textures = new Dictionary<string, Texture2D>();

            using (FileStream file = new FileStream(game.Content.RootDirectory + "\\" + ConfigFileName, FileMode.Open))
            {
                StreamReader Reader = new StreamReader(file);

                string line;
                while (Reader.EndOfStream == false)
                {
                    line = Reader.ReadLine();
                    string[] words = line.Split(new char[] { ' ', '\t', '\n', '\0' }, StringSplitOptions.RemoveEmptyEntries);

                    Debug.Assert(words.Length == 3);

                    _FileNames.Add(words[0], words[1]);
                    if (words[2] != "_")
                        _TextureNames.Add(words[0], words[2]);

                    //if (words[1] != "-")
                    //    _Textures.Add(words[0], game.Content.Load<Texture2D>(words[2]));
                }
            }

            ConfigFileName = "Data\\Doodads.txt";
            using (FileStream file = new FileStream(game.Content.RootDirectory + "\\" + ConfigFileName, FileMode.Open))
            {
                StreamReader Reader = new StreamReader(file);

                string line;
                while (Reader.EndOfStream == false)
                {
                    line = Reader.ReadLine();
                    string[] words = line.Split(new char[] { ' ', '\t', '\n', '\0' }, StringSplitOptions.RemoveEmptyEntries);

                    Debug.Assert(words.Length == 2);

                    _FileNames.Add(words[0], words[1]);
                }
            }

            _DoodadRenderer = new Dictionary<string, DoodadRenderer>();

            ConfigFileName = "Data\\DoodadsFiles.txt";
            using (FileStream file = new FileStream(game.Content.RootDirectory + "\\" + ConfigFileName, FileMode.Open))
            {
                StreamReader Reader = new StreamReader(file);

                string line;
                while (Reader.EndOfStream == false)
                {
                    line = Reader.ReadLine().Trim();

                    AddDoodadRenderer(line, game);
                }
            }

            AddDoodadRenderer("SelectionCircle", "UI\\Feedback\\selectioncircle\\selectioncircle", game);
            _DebugRecords = new List<string>();
        }

        private void AddDoodadRenderer(string shortName, string ModelName, Game game)
        {
            MDX.Model model = game.Content.Load<MDX.Model>(ModelName);
            _DoodadRenderer.Add(shortName, new DoodadRenderer(game.GraphicsDevice, model));
        }

        private void AddDoodadRenderer(string ModelName, Game game)
        {
            MDX.Model model = game.Content.Load<MDX.Model>(ModelName);
            _DoodadRenderer.Add(ModelName, new DoodadRenderer(game.GraphicsDevice, model));
        }

        private void GenerateDoodads(string prefix, int number, Game game)
        {
            string name;

            name = prefix + Convert.ToChar(number + '0');
            AddDoodadRenderer(name, game);

            name = prefix + Convert.ToChar(number + '0') + 'S';
            AddDoodadRenderer(name, game);

            name = prefix + Convert.ToChar(number + '0') + 'D';
            AddDoodadRenderer(name, game);
        }

        public PaletteRenderer GetPaletteRenderer(string name)
        {
            return _DoodadRenderer[name];
        }

        public static string GetName(Tree tree, Vector3 Position, out Texture2D texture)
        {
            texture = null;

            // Here, Lost "D00B" and "D009", of 200 entities
            if (_FileNames.ContainsKey(tree.TreeType))
            {
                string TreeName = _FileNames[tree.TreeType];

                string Name = null;
                string textureName = null;

                if (_DoodadRenderer.ContainsKey(TreeName))
                {
                    Name = TreeName;
                    if (_TextureNames.ContainsKey(tree.TreeType))
                        textureName = _TextureNames[tree.TreeType];
                }
                else
                {
                    string aName = TreeName + Convert.ToChar(tree.Variation + '0');
                    if (_DoodadRenderer.ContainsKey(aName))
                    {
                        Name = aName;
                        if (_TextureNames.ContainsKey(tree.TreeType))
                            textureName = _TextureNames[tree.TreeType];
                    }

                    if (tree.Flag == 1 || tree.Flag == 0)
                        return null;
                }

                if (Name != null)
                {
                    if (textureName != null)
                    {
                        if (tree.TreeType == "ATtr")
                        {
                            // Here, we should get terrain type, then assign the correct tree texture
                            if (GameplayWorld.Instance.PathManager.CheckType(Position, EPathType.IsBlight))
                            {
                                texture = _Game.Content.Load<Texture2D>("ReplaceableTextures\\AshenvaleTree\\AshenTreeBlight");
                            }
                            else
                            {
                                texture = _Game.Content.Load<Texture2D>("ReplaceableTextures\\AshenvaleTree\\AshenTree");
                            }
                        }
                        else
                        {
                            if (_Textures.ContainsKey(tree.TreeType) == false)
                            {
                                texture = _Game.Content.Load<Texture2D>(textureName);
                                _Textures.Add(tree.TreeType, texture);
                            }
                            texture = _Textures[tree.TreeType];
                        }
                    }
                    return Name;
                }

                if (_DebugRecords.Contains(TreeName) == false)
                    _DebugRecords.Add(TreeName);

                return null;
            }
            else
            {
                return null;
            }
        }

        public static void PrintDebugRecords()
        {
            _DebugRecords.Sort();
            for (int i = 0; i < _DebugRecords.Count; i++)
                Debug.WriteLine(_DebugRecords[i]);
        }
    }
}
